#!/bin/sh -x

#
# Script to setup running Susan regression tests
#

SUSAN_SOURCE=$(cd .. && pwd)

check_exit_code()
{
   if [ $? != 0 ] ; then
      echo "Bad exit code giving up"
      exit 1
   fi
}

. ./config

cwd=`pwd`
if [ ! -d ${SUSAN_SOURCE} ] ; then
   echo "The SUSAN_SOURCE environment variable must be a Susan release directory, but is not."
   echo " "
   exit 1
fi

MAKEOPTS=${MAKEOPT:-"-j8"}

#
# We build and setup binaries to the $cwd/bin directory not $bin
#
rm -rf bin

if [ -f ${SUSAN_SOURCE}/.git/config ] && type git >/dev/null 2>&1; then
    #
    # update susan sources
    #
    (
        cd ${SUSAN_SOURCE};
        git show HEAD | grep commit | head -1 | awk '{print $2}' > git-version
    )
else
    echo "Git not available." > build/git-version
fi

scripts/create_sed



sed -f tmp/sed_tmp scripts/regress-config.in >scripts/regress-config
chmod 755 scripts/regress-config

#
# Run Susan configuration, make, install
#
sh -x ../regress/scripts/regress-config ${cwd}
check_exit_code

make -C build ${MAKEOPT}
check_exit_code
make -C build install
check_exit_code
make -C build ${MAKEOPT} test
check_exit_code

#  TargetDirectories for gcov
mkdir CMakeFiles
#cp build/CMakeFiles/TargetDirectories.txt CMakeFiles
echo ${cwd} >> CMakeFiles/TargetDirectories.txt

cd ${cwd}
bin/susan stop

mkdir -p working
# make sure everything is cleaned up
touch working/CLEANUPMARKER

cd bin
echo "Running database creation scripts"
./create_susan_database ${DBTYPE}
./drop_susan_tables ${DBTYPE}
./make_susan_tables ${DBTYPE}
./grant_susan_privileges ${DBTYPE}

echo "initializing database driver"
./susan-config initialize_database_driver

cd ${cwd}

rm_if_exists() {
   if [ -e $1 ]; then
      rm -f $1
   fi
}

#
# Build webui
#


sh -x ../regress/scripts/regress-config-webui ${cwd}
check_exit_code

make -C build-webui install
check_exit_code

mv bin/susan-dir.d/console/admin.conf.example bin/susan-dir.d/console/admin.conf

echo "webui can be started with  'php -S 127.0.0.1:9100 -t ../webui/public/'"

exit 0
